package com.solidtrust.admin.controller;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.solidtrust.app.MD5PasswordEncoder;
import com.solidtrust.entity.UserInfo;



@Controller
public class LoginController {

	@PersistenceContext EntityManager em;
	@Autowired MD5PasswordEncoder passwordEncoder;
	
	@RequestMapping("/login")
	public String home(){
		return "index.jsp";
	}
	
	@RequestMapping(value = "loginSuccess")
	public String loginSuccess(HttpSession session){
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		session.setAttribute("user", em.find(UserInfo.class, auth.getName()));
		return "redirect:/";
	}
	
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login(){
		return "login.jsp";
	}
	
	@RequestMapping(value = "home.html")
	public String index(){
		return "index.jsp";
	}
	
	@Transactional(readOnly = false)
	@RequestMapping(value = "/changePwd", method = {RequestMethod.POST})
	public @ResponseBody String changePwd(@RequestParam(required = true) String pwd, HttpSession session){
		UserInfo u = (UserInfo) session.getAttribute("user");
		u.setPassword(passwordEncoder.encode(pwd));
		em.merge(u);
		return "ok";
	}
}
